<?php
class Lib_Application_Resource_Utils extends Zend_Application_Resource_ResourceAbstract {

    /**
     * @var Zend_Config
     */
    private $_config;

    /**
     * @var Zend_Application
     */
    protected $_application;

    public function init() {
        $this->setConfig(Zend_Registry::get('config'));
        $this->_initRoutes();
    }

    protected function _initRoutes(){
        /**
         * @TODO Write cache management
         */
        
        $options = $this->getOptions();
        $routesConfig = new Zend_Config_Ini($options['routes']['path'], APPLICATION_ENV);
        $frontController = Zend_Controller_Front::getInstance();
        $router = $frontController->getRouter();

        // Add main routes section

        if(count($routesConfig)){
            $router->addConfig($routesConfig,'routes');
        }
        // Add additional routes taken from modules
        $modules = $this->getConfig()->resources->modules;
        if($modules){
            $modules = $modules->toArray();
            foreach($modules as $moduleIndex=>$moduleName){
                 $modulePath = $frontController->getModuleDirectory($moduleName);
                 // Add routes chain
                 $routeChain = new Zend_Config_Ini($modulePath . '/configs/routes.ini', APPLICATION_ENV);
                 if(count($routeChain)){
                     $router->addConfig($routeChain, 'routes');
                 }
            }
        }
    }

    public function setConfig($config) {
        $this->_config = $config;
    }

    public function getConfig() {
        return $this->_config;
    }
}